import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter_dva_hooks/flutter_dva_hooks.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:todo_app/components/FontIcon.dart';
import 'package:todo_app/components/TextExt.dart';
import 'package:todo_app/constants/DColor.dart';
import 'package:todo_app/controllers/StatisticsController.dart';
import 'package:todo_app/controllers/TodoController.dart';
import 'package:todo_app/controllers/definitions/MyStatisticsModel.dart';
import 'package:todo_app/controllers/definitions/TodoModel.dart';
import 'package:todo_app/hooks/EasyRefreshController.dart';
import 'package:todo_app/layout/Gaps.dart';
import 'package:todo_app/layout/ListItem.dart';
import 'package:todo_app/layout/Space.dart';
import 'package:todo_app/models/getters.dart';
import 'package:todo_app/utils/AppNavigator.dart';
import 'package:todo_app/utils/ExtHelper.dart';

class MePage extends HookWidget {
  const MePage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    useAutomaticKeepAlive();
    var store = useDvaStore();
    var user = store.rootState.system?.user;

    var pageData = useState<PageData<TodoModel>>(PageData<TodoModel>());
    var pagination = useState<Pagination>(Pagination());
    var controller = useEasyRefreshController(
      controlFinishRefresh: true,
      controlFinishLoad: true
    );
    var stat = useState<MyStatisticsModel?>(null);

    useEffect(()  {
      TodoController.collectListUsingGet(pageData.value.current, pageData.value.pageSize).then((res) {
        if(res.status == 'success') {
          var data = PageData<TodoModel>();
          data.current = res.data?.current ?? 1;
          data.total = res.data?.total ?? 0;
          data.pageSize = pageData.value.pageSize;
          data.data = pageData.value.data;
          data.records = pageData.value.records;
          if(data.current == 1) {
            controller.finishRefresh();
            data.firstPage(res.data?.records ?? []);
          } else {
            data.addPage(data.current, res.data?.records ?? []);
          }
          pageData.value = data;
          if(data.hasMore) {
            controller.finishLoad();
          } else {
            controller.finishLoad(IndicatorResult.noMore, true);
          }
        }
      });
      return () {};
    }, [pagination.value.current, pagination.value.refreshKey]);

    useEffect(() {
      StatisticsController.myUsingGet().then((res) {
        if(res.status == 'success') {
          stat.value = res.data;
        }
      });
      return () {};
    }, [pagination.value.refreshKey]);

    return CustomScrollView(
      slivers: [
        SliverAppBar(
          leading: const FontIcon(icon: FontIcons.user),
          title: Text(user?.nickname ?? user?.username ?? ""),
          backgroundColor: DColor.primary,
        ),
        SliverToBoxAdapter(
          child: Container(
            color: DColor.primary,
            padding: EdgeInsets.symmetric(
              vertical: 20.dp
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                MeTextButton(title: "分组", number: stat.value?.group ?? 0, onTap:() {
                  AppNavigator.go('/tabs/group');
                }),
                MeTextButton(title: "待办事项", number: stat.value?.todo ?? 0, onTap:() {
                  AppNavigator.go('/tabs/home');
                }),
                MeTextButton(title: "收藏", number: stat.value?.collect ?? 0, onTap:() {
                  AppNavigator.pushNamed('todoCollectList');
                }),
                MeTextButton(title: "历史事项", number: stat.value?.history ?? 0, onTap:() {
                  AppNavigator.pushNamed('todoHistoryList');
                }),
              ],
            ),
          ),
        ),
        SliverToBoxAdapter(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              ListItem(
                height: 44.dp,
                margin: EdgeInsets.only(
                  top: 12.dp
                ),
                bgColor: Colors.white,
                icon: FontIcon(icon: FontIcons.cog, size: 14.dp,),
                title: TextExt.title("设置", lineHeight: 1),
                nextIcon: true,
                onTap: () {
                  AppNavigator.pushNamed('meSettings');
                },
              )
            ],
          )
        ),
        const SliverFillRemaining()
      ],
    );
  }
}


class MeTextButton extends StatelessWidget {
  final String title;
  final int number;
  final VoidCallback onTap;

  const MeTextButton({super.key, required this.title, required this.number, required this.onTap});

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onTap,
      child: Space(
        vertical: true,
        height: 64.dp,
        children: [
          TextExt.body(title, fontSize: 12.dp, style: const TextStyle(color: Colors.white)),
          TextExt.title(number.toStringAsFixed(0), bold: true, fontSize: 18.dp, style: const TextStyle(color: Colors.white)),
        ]
      )
    );
  }
}
